package com.landeb.shop.huo.act;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.adapter.ActShopsCollectionLVAdapter;
import com.landeb.shop.huo.bean.BeanActShopsCollectionLV;
import com.landeb.shop.huo.bean.BeanStatusInfo;
import com.landeb.shop.huo.httpRequest.ActShopsCollectionRequest;
import com.landeb.shop.huo.view.FootView;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ShopsCollectionActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout btnBack;
    private ListView mListView;
    private SwipeRefreshLayout mSRL;

    private List<BeanActShopsCollectionLV.DataBean.ListBean> mShops = new ArrayList<>();
    private FootView mFootView;
    private ActShopsCollectionLVAdapter mAdapter;

    private String mUrl;
    private Retrofit mRetrofit;
    private ActShopsCollectionRequest mRequest;
    private int page = 0;
    private boolean hasNextPage = true;
    private boolean isRefreshing = false;
    private boolean isLoading = false;
    private boolean isRemoving = false;

    public static void toAct(Context context) {
        Intent intent = new Intent(context, ShopsCollectionActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shops_collection);

        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(ActShopsCollectionRequest.class);

        initView();
        initData();
        initEvent();
        refresh();

    }

    private void loadMore() {

        page++;

        if (!isLoading && hasNextPage) {

            isLoading = true;
            mFootView.setRefreshing();

            mRequest.getShops(page, 10)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanActShopsCollectionLV>() {
                        @Override
                        public void onCompleted() {
                            isLoading = false;
                        }

                        @Override
                        public void onError(Throwable e) {
                            isLoading = false;
                        }

                        @Override
                        public void onNext(BeanActShopsCollectionLV beanActShopsCollectionLV) {

                            if (beanActShopsCollectionLV.getStatus() == 1) {

                                mShops.addAll(beanActShopsCollectionLV.getData().getList());
                                mAdapter.notifyDataSetChanged();

                                if (beanActShopsCollectionLV.getData().getMore() == 1) {
                                    hasNextPage = true;
                                    mFootView.setToRefresh();
                                } else {
                                    hasNextPage = false;
                                    mFootView.setFinished();
                                }

                            } else {
                                Toast.makeText(ShopsCollectionActivity.this, beanActShopsCollectionLV.getInfo(), Toast.LENGTH_SHORT).show();
                            }

                        }
                    });

        }

    }

    private void refresh() {

        mSRL.setRefreshing(true);

        page = 1;
        hasNextPage = true;

        if (!isRefreshing) {

            isRefreshing = true;

            mRequest.getShops(page, 10)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanActShopsCollectionLV>() {
                        @Override
                        public void onCompleted() {
                            mSRL.setRefreshing(false);
                            isRefreshing = false;

                        }

                        @Override
                        public void onError(Throwable e) {
                            mSRL.setRefreshing(false);
                            isRefreshing = false;
                        }

                        @Override
                        public void onNext(BeanActShopsCollectionLV beanActShopsCollectionLV) {

                            if (beanActShopsCollectionLV.getStatus() == 1) {

                                mShops.clear();
                                mShops.addAll(beanActShopsCollectionLV.getData().getList());
                                mAdapter.notifyDataSetChanged();

                                if (beanActShopsCollectionLV.getData().getMore() == 1) {
                                    hasNextPage = true;
                                    mFootView.setToRefresh();
                                } else {
                                    hasNextPage = false;
                                    mFootView.setFinished();
                                }

                            } else {
                                Toast.makeText(ShopsCollectionActivity.this, beanActShopsCollectionLV.getInfo(), Toast.LENGTH_SHORT).show();
                            }

                        }
                    });

        }

    }

    private void initEvent() {

        btnBack.setOnClickListener(this);

        mSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        mAdapter = new ActShopsCollectionLVAdapter(this, mShops);
        mListView.setAdapter(mAdapter);
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        loadMore();

                    }
                }

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // TODO: 2016/11/12 单击事件

//                Toast.makeText(ShopsCollectionActivity.this, mShops.get(i).getStore_id(), Toast.LENGTH_SHORT).show();

                ShopDetailActivity.toAct(ShopsCollectionActivity.this,mShops.get(i).getStore_id());
            }
        });

        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                final String shopId = mShops.get(i).getStore_id();
                final int position = i;

                AlertDialog.Builder builder = new AlertDialog.Builder(ShopsCollectionActivity.this);
                builder.setMessage("确认取消关注  " + mShops.get(i).getName())
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                if (!isRemoving) {

                                    isRemoving = true;

                                    mRequest.cancelShops(shopId)
                                            .subscribeOn(Schedulers.io())
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .subscribe(new Subscriber<BeanStatusInfo>() {
                                                @Override
                                                public void onCompleted() {
                                                    isRemoving = false;
                                                }

                                                @Override
                                                public void onError(Throwable e) {
                                                    isRemoving = false;

                                                }

                                                @Override
                                                public void onNext(BeanStatusInfo beanStatusInfo) {

                                                    if (beanStatusInfo.getStatus() == 1) {
                                                        mShops.remove(position);
                                                        mAdapter.notifyDataSetChanged();
                                                    } else {
                                                        Toast.makeText(ShopsCollectionActivity.this, beanStatusInfo.getInfo(), Toast.LENGTH_SHORT).show();
                                                    }

                                                }
                                            });

                                }

                            }
                        })
                        .setNegativeButton("取消", null)
                        .setCancelable(false)
                        .show();

                return true;
            }
        });

    }

    private void initData() {

//        for (int i = 0; i < 30; i++) {
//
//            BeanActShopsCollectionLV.DataBean.ListBean b =new BeanActShopsCollectionLV.DataBean.ListBean();
//            b.setFavorite(i+"");
//            b.setName(i+"");
//            b.setStore_id(i+"");
//            mShops.add(b);
//        }


    }

    private void initView() {

        btnBack = (LinearLayout) findViewById(R.id.act_shops_collection_btn_back);

        mSRL = (SwipeRefreshLayout) findViewById(R.id.activity_shops_collection_refresh);
        mSRL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));


        mListView = (ListView) findViewById(R.id.activity_shops_collection_lv);
        mFootView = new FootView(this);
        mListView.addFooterView(mFootView, null, false);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.act_shops_collection_btn_back:

                onBackPressed();
                break;

        }
    }
}
